<template>
  <div
    class="cell-swipe-item"
    :style="move"
    @touchstart.capture="touchStart"
    @touchmove.capture="touchMove"
    @touchend.capture="touchEnd"
  >
    <slot />
    <div
      class="operate"
      :style="opRight"
    >
      <div
        class="op-item"
        v-for="(op, index) in right"
        :key="index"
        :style="op.style"
        @click="op.handler"
      >
        {{ op.content }}
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'ZybCellSwipeItem',
  props: {
    right: {
      type: Array,
      default: () => [],
    },
    id: Number,
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      btnWdith: '',
      sliding: 0,
    };
  },
  inject: ['Cellswipe'],
  computed: {
    opRight() {
      return `right:-${this.right.length * this.btnWdith}px`;
    },
    move() {
      return `transform: translateX(-${this.sliding * this.btnWdith}px)`;
    },
    expand() {
      return this.Cellswipe.activeVal === this.id;
    },
  },
  watch: {
    expand: {
      immdiate: true,
      handler(nVal) {
        if (!nVal) {
          this.sliding = 0;
        }
      },
    },
  },
  methods: {
    // 滑动开始
    touchStart(e) {
      // 记录初始位置
      this.startX = e.touches[0].clientX;
      const target = e.currentTarget || e.target;
      // 当前滑动的父级元素
      const { parentElement } = target;
      this.num = parentElement.getElementsByClassName('btn').length;
      this.Cellswipe.handleItemTouch(this.id);
    },
    touchMove(e) {
      this.moveX = e.touches[0].clientX;
      // 左滑
      if (this.startX - this.moveX > 30 && this.sliding === 0 && !this.disabled) {
        this.sliding = this.right.length;
      }
      // 右滑
      if (this.startX - this.moveX < -30 && this.sliding !== 0) {
        this.sliding = 0;
      }
    },
    // 滑动结束
    touchEnd() {
      this.startX = 0;
      this.moveX = 0;
      this.endX = 0;
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.btnWdith = document.getElementsByClassName('op-item')[0].offsetWidth;
    });
  },
};
</script>
<style lang="less">
@import "../style/cellSwipeItem.less";
</style>
